package com.winit.cloudlink.mgmt.recovery;

import com.winit.cloudlink.message.Message;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

@Slf4j
public class MessageRestoreTask {
    private MessageSender messageSender;
    private String messageFile;
    private MessageReader messageReader;

    public MessageRestoreTask(String messageFile, MessageSender messageSender) {
        this.messageFile = messageFile;
        this.messageSender = messageSender;
    }

    public long execute() {
        messageReader = new FileMessageReader();
        return restoreMessageFromFile(new File(messageFile));
    }

    protected long restoreMessageFromFile(File file) {
        log.info("正在从文件'{}'里恢复消息...", file.getName());
        SimpleMessageReaderHandler messageReaderHandler = new SimpleMessageReaderHandler();
        messageReader.read(file, messageReaderHandler);
        log.info("从文件'{}'里恢复消息已完成，共恢复{}条消息.", file.getName(), messageReaderHandler.getCount());
        return messageReaderHandler.getCount();
    }

    private class SimpleMessageReaderHandler implements MessageReaderHandler {
        private long count = 0;

        public SimpleMessageReaderHandler() {
            Timer timer = new Timer();
            timer.schedule(new LogTimerTask(), 1, 1000);
        }

        @Override
        public void process(Message message) {
            messageSender.sendMessage(message);
            count++;
        }

        public long getCount() {
            return count;
        }

        class LogTimerTask extends TimerTask {
            private long previous = 0;

            public void run() {
                if (count > previous) {
                    log.info("正在从文件'{}'里恢复消息，已恢复{}条消息.", messageFile, count);
                    previous = count;
                }
            }
        }
    }
}
